package dsk.demo.product.controller.supplier;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dsk.demo.common.utils.PageUtils;
import dsk.demo.common.utils.R;
import dsk.demo.product.dto.SupplierProductQueryDto;
import dsk.demo.product.dto.SupplierProductSaveDto;
import dsk.demo.product.entity.ProductEntity;
import dsk.demo.product.entity.SupplierProductRefEntity;
import dsk.demo.product.service.SupplierProductRefService;
import dsk.demo.product.vo.SupplierProductVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 供应商产品 管理
 */
@RestController
@RequestMapping("supplier/product")
public class SupplierProductRefController {

    @Autowired
    SupplierProductRefService supplierProductRefService;

    /**
     * 新增
     */
    @RequestMapping("/save")
    public R save(@RequestBody SupplierProductRefEntity entity){
        try {
                supplierProductRefService.saveOrUpdate(entity);
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            return R.error(501,"新增供应商产品失败");
        }
        return R.ok();
    }

    /**
     * 分页查询
     */
    @RequestMapping("/list")
    public R list(@RequestBody SupplierProductQueryDto queryDto){
        try {
            PageUtils list = supplierProductRefService.querySupplierProductPage(queryDto);
            return R.ok().put("page", list);
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            return R.error(501,"新增供应商产品失败");
        }
    }

    /**
     * 批量上传  所需的模板下载
     */
    @RequestMapping("/downloadTemp")
    public void downloadTemp(HttpServletResponse response) throws IOException {
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //配置别名
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("productNo","本厂编号");
        map.put("supplierProductNo","工厂产品编号");
        map.put("price","工厂交货价");
        map.put("remark","备注");
        writer.setHeaderAlias(map);
        //只写入配置了别名的属性
        writer.setOnlyAlias(true);

        SupplierProductSaveDto productEntity = new SupplierProductSaveDto();
        List<SupplierProductSaveDto> rows = new ArrayList<>();
        rows.add(productEntity);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=supplierProductTemp.xls");
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    /**
     * excel批量上传
     */
    @RequestMapping("/saveList/{supplierId}")
    public R saveList(MultipartFile file, @PathVariable Long supplierId){
        try {
            List<SupplierProductRefEntity> productEntities = supplierProductRefService.excel2ProductEntityList(file);
            for (SupplierProductRefEntity productRefEntity : productEntities) {
                productRefEntity.setSupplierId(supplierId);
            }

            supplierProductRefService.insertBatch(productEntities);
            return R.ok();
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            return R.error(501,"上传失败");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        try {
            supplierProductRefService.removeByIds(Arrays.asList(ids));
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            return R.error(501,"删除供应商失败");
        }
        return R.ok();
    }



}
